import jwt
import datetime
# from django.conf import settings
from django.conf import settings
import time

def create_token(user_id:int, timeout=settings.JWT_TOKEN_EXP):
    '''
    :param user_id: 传递用户的id
    :param timeout: token有效时间，默认是一天
    :return:
    '''
    payload = {'user_id':user_id}
    salt = settings.SECRET_KEY #加密的盐
    # 构造header
    headers = {
        'type': 'jwt',
        'alg': 'HS256'
    }
    # payload,用户登录成功后，传递payload={'user_id':user.id,'username':user.name}
    # 构造payload,exp超时时间，单位分钟
    # payload['exp'] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout) #使用utc时间
    now_datetime = time.time()
    payload['exp'] = now_datetime + timeout #token过期时间,时间戳
    # print(payload)
    token = jwt.encode(payload=payload, key=salt, algorithm="HS256", headers=headers).decode('utf-8')
    return token
